﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace MsnTrackerPlugin
{
    static class Utility
    {
        #region 发送MSN消息
        private const short WM_COPYDATA = 74;
        public struct COPYDATASTRUCT
        {
            public int dwData;
            public int cbData;
            public int lpData;
        }

        [DllImport("user32", EntryPoint = "SendMessageA")]
        private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32", EntryPoint = "FindWindowExA")]
        private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);

        public static int VarPtr(object e)
        {
            GCHandle GC = GCHandle.Alloc(e, GCHandleType.Pinned);
            int gc = GC.AddrOfPinnedObject().ToInt32();
            GC.Free();
            return gc;
        }

        public static void SendMSNMessage(bool enable, string category, string message)
        {
            String buffer = "\\0" + category + "\\0" + (enable ? "1" : "0") + "\\0{0}\\0" + message + "\\0\\0\\0\\0\0";
            int handle = 0;

            COPYDATASTRUCT data;
            data.dwData = 0x0547;
            data.lpData = VarPtr(buffer);
            data.cbData = buffer.Length * 2;

            handle = FindWindowEx(0, handle, "MsnMsgrUIManager", null);
            if (handle > 0)
                SendMessage(handle, WM_COPYDATA, 0, VarPtr(data));
        }
        #endregion
    }
}
